// pages/newsinfo/newsinfo.js
import { getsockertId,getnews,getShopDetail,getaddress,createOrder } from '../../utils/api'
import {formatTime} from '../../utils/util'
Page({
  data: {
    showPopup:false,//弹窗开关
    showPopup2:false,//地址弹窗开关
    popupBottom: -300,//过度高
    popupBottom2: -300,//过度高
    addresslist:[],//地址列表
    address:{},//所选地址
    goods:{},//商品信息
    messages: [], // 聊天消息数组
    inputValue: '', // 输入框内容
    receiverId: '', // 接收者 
    id:'', //所属列表id
    gid:''//商品id
  },

  // 页面加载时获取历史聊天记录
  onLoad: function(obj) {
    // console.log(obj)
    this.setData({
      receiverId:obj.otherid,
      id:obj.id,
      gid:obj.gid
    })
    this.Getnews()
    this.getgoods()
    
    this.initWebSocket();
  },
  //获取商品信息
  async getgoods(){
    const {data:res} = await getShopDetail(this.data.gid)
    console.log(res)
    if(res.data.code == 200){
      res.data.data.url = JSON.parse(res.data.data.url)[0]
      res.data.data.zong = Number(res.data.data.shipping_cost.trim()) + Number(res.data.data.price.trim())
      this.setData({
        goods:res.data.data
      })
    }
  },
  // 输入框内容改变
  onInputChange: function(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  //初始化socket
  initWebSocket () {
    const token = wx.getStorageSync('token');
    wx.connectSocket({
      url: 'ws://127.0.0.1:3001',
      header: {
        'content-type': 'application/json',
        'token':token
      },
      success: (res) => {
        console.log('WebSocket 连接成功', res);
      },
      fail: (err) => {
        console.error('WebSocket 连接失败', err);
      }
    });

    // 监听 WebSocket 连接打开事件
    wx.onSocketOpen((res) => {
      console.log('WebSocket 连接已打开', res);
    });

    // 监听 WebSocket 接收消息事件
    wx.onSocketMessage((res) => {
      const message = res.data;
      console.log(message)
      const [newmessage,uid,gid] = message.split('::');
      console.log(gid,this.data.gid)
      if(gid != this.data.gid) return
      const {messages} = this.data
          const new_messages = [...messages] 
          new_messages.push({
            content:newmessage,
            create_date:formatTime(new Date()),
            uid:uid
          })
          this.setData({
            messages:new_messages,
            inputValue:'',
          })
    });

    // 监听 WebSocket 连接关闭事件
    wx.onSocketClose((res) => {
      console.log('WebSocket 连接已关闭', res);
    });

    // 监听 WebSocket 错误事件
    wx.onSocketError((res) => {
      console.log('WebSocket 发生错误', res);
    });
    
  },
  //向服务端发消息
  sendMessage: async function () {
    const { inputValue, receiverId,id } = this.data;
    if (inputValue.trim() === '') return;
    const {data:res} = await getsockertId(receiverId)
    if(res.data.code !=200) return wx.showToast({
      title: '参数获取失败',
      icon: 'none',
      duration: 2000,
      mask:true
    });

    const {socket_id,id:uid} = res.data.data
      const {gid} = this.data
      wx.sendSocketMessage({
        //targetClientId--socketid  inputValue--消息内容  receiverId---对方id  id---列表id  uid--当前用户id  gid --商品id
        data: `${socket_id}::${inputValue}::${receiverId}::${id}::${uid}::${gid}`,
        success: (res) => {
          console.log('发送消息成功', res);
          const {messages} = this.data
          const new_messages = [...messages] 
          new_messages.push({
            content:inputValue,
            create_date:formatTime(new Date()),
            uid:uid
          })
          this.setData({
            messages:new_messages,
            inputValue:''
          })
          
        },
        fail: (err) => {
          console.error('发送消息失败', err);
        }
      });

  },
  //获取消息
  async Getnews(){

    const {data:res} = await getnews(this.data.id)
    console.log(res.data)
    if(res.data.code == 200){
      this.setData({
        messages: res.data.data
      })
    }else{
      wx.showToast({
        title: '获取列表失败',
        icon: 'none',
        duration: 2000,
        mask:true
      });
    }
  },
  //立即购买--弹窗
  openbuy(){
    this.getaddressList()
    this.setData({
      popupBottom: 0,
      showPopup:true
    })
  },
  //关闭弹窗
  closePopup(){
    if(this.data.showPopup2) return
    let w = wx.getSystemInfoSync().windowHeight
    this.setData({
      popupBottom: -w+(-w*1/2)+(-w*1/4),
    })
    setTimeout(() => {
      this.setData({
        showPopup: false
      });
    }, 300); 
  },
  //获取地址
  async getaddressList(){
    const {data:res} = await getaddress()
    console.log(res)
    if(res.data.code == 200){
      this.setData({
        addresslist:res.data.data,
        address:res.data.data[0]
      })
    }
  },
  //打开选择地址
  openchangeaddress(){
    this.setData({
      popupBottom2: 0,
      showPopup2:true
    })
  },
  //关闭地址弹窗
  closePopup2(){
    let w = wx.getSystemInfoSync().windowHeight
    this.setData({
      popupBottom2: -2*w,
    })
    setTimeout(() => {
      this.setData({
        showPopup2: false
      });
    }, 300); 
  },
  //选择地址
  changeaddress(e){
    const {id} = e.currentTarget.dataset
    // console.log(this.data.addresslist[id])
    this.setData({
      address:this.data.addresslist[id]
    })
    this.closePopup2()
  },
  //确认购买
  async sureBuy(){
    const {gid,goods,address} = this.data
    // console.log(gid,goods.zong,address.receiver_phone,address.receiver_name,address.address)
    const {data:res} = await createOrder({
      gid:gid,
      zong:goods.zong,
      receiverPhone:address.receiver_phone,
      receiverName:address.receiver_name,
      address:address.address
    })
    console.log(res) 
    if(res.data.code == 200){
      wx.showModal({
        title: '沙箱支付地址',
        content: '确认复制地址到剪贴板',
        showCancel: false,
        success: (restult) => {
          if (restult.confirm) {
            // 复制地址到剪贴板
            wx.setClipboardData({
              data: res.data.paymentUrl,
              success: () => {
                wx.showToast({
                  title: '复制成功',
                  icon: 'success',
                  duration: 2000,
                  mask:true
                });
                setTimeout(()=>{
                  wx.navigateTo({
                    url: `/pages/payresult/payresult?id=${res.data.order}&&price=${goods.zong}`,
                  })
                },2000)
              },
              fail: () => {
                wx.showToast({
                  title: '复制失败',
                  icon: 'error',
                  duration: 2000,
                  mask:true
                });
              }
            });
          }
        }
      });
    }
  },
  //页面卸载
  onUnload: function () {
    return
    // 关闭 WebSocket 连接
    wx.closeSocket({
      success: (res) => {
        console.log('WebSocket 连接关闭成功', res);
      },
      fail: (err) => {
        console.error('WebSocket 连接关闭失败', err);
      }
    });
  }



});